package ar.edu.uba.fi.jmit.integrationcommons.comparator;

import java.io.Serializable;
import java.util.Comparator;

import ar.edu.uba.fi.jmit.integrationcommons.Message;
import ar.edu.uba.fi.jmit.integrationcommons.MessagePriority;
import ar.edu.uba.fi.jmit.integrationcommons.exception.IntegrationRuntimeException;
/**
 * Compara dos mensajes por su prioridad. El resultado del comparator es 1 si el primero
 * de los mensajes tiene mayor prioridad, -1 si tiene menor prioridad y 0 si son iguales.
 * @author Tomas
 *
 */
public class MessagePriorityComparator implements Comparator<Message>, Serializable {
	
	private static final long serialVersionUID = 6902462968874544617L;

	private final static int FIRST_ARGUMENT_SMALLER = -1;
	
	private final static int FIRST_ARGUMENT_BIGGER = 1;
	
	private final static int EQUALS = 0;
	
	@Override
	public int compare(Message message1, Message message2) {
		if(!hasPriority(message1)) {
			if(hasPriority(message2)) {
				return FIRST_ARGUMENT_SMALLER;
			}else {
				return EQUALS;
			}
		}
		if(!hasPriority(message2)) {
			return FIRST_ARGUMENT_BIGGER;
		}
		return getValueForPriority(message1.getHeader().getPriority())
		.compareTo(getValueForPriority(message2.getHeader().getPriority()));
	}
	
	private Integer getValueForPriority(MessagePriority priority) {
		if(MessagePriority.HIGH_PRIORITY.equals(priority)) {
			return 1;
		}
		if(MessagePriority.NORMAL.equals(priority)) {
			return -1;
		}
		throw new IntegrationRuntimeException(priority + " is not a valid priority for the comparator");
	}

	private boolean hasPriority(Message message) {
		return !(message == null || 
				message.getHeader() == null || 
				message.getHeader().getPriority() == null);
	}

}
